﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Security;
using System.ServiceModel;
using System.ServiceModel.Description;
using System.Configuration;
using System.Web;
using System.Web.Caching;


using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Query;
using Microsoft.Xrm.Sdk.Messages;
using Microsoft.Xrm.Sdk.Discovery;
using Microsoft.Xrm.Sdk.Client;





namespace CommonLibrary
{
    public class CrmSvcHelper
    {
        #region const
        private const string SERVICE_CACHE_KEY = "SERVICE_CACHE";
        private const int SERVICE_CACHE_EXPIRE_MINUTES = 30;
        #endregion


        public static IOrganizationService CreateService()
        {
            //get service from cache
            if (HttpContext.Current != null && HttpContext.Current.Cache != null && HttpContext.Current.Cache.Get(SERVICE_CACHE_KEY) != null)
            {
                return (IOrganizationService)HttpContext.Current.Cache.Get(SERVICE_CACHE_KEY);
            }
            else
            {
                Uri orgUri = new Uri(ConfigurationManager.AppSettings["orgSvcPath"]);
                OrganizationServiceProxy service;
                System.ServiceModel.Description.ClientCredentials credentials = new ClientCredentials();
                credentials.Windows.ClientCredential = new NetworkCredential(
                                                                               ConfigurationManager.AppSettings["invokerAccount"]
                                                                               , ConfigurationManager.AppSettings["invokerAccountPwd"]
                                                                               , ConfigurationManager.AppSettings["invokerDomain"]
                                                                             );
                service = new OrganizationServiceProxy(orgUri, null, credentials, null);
                service.ServiceConfiguration.CurrentServiceEndpoint.Behaviors.Add(new ProxyTypesBehavior());

                // save service in cache
                if (HttpContext.Current != null && HttpContext.Current.Cache != null)
                {
                    HttpContext.Current.Cache.Insert(SERVICE_CACHE_KEY, service, null, DateTime.Now.AddMinutes(SERVICE_CACHE_EXPIRE_MINUTES), System.Web.Caching.Cache.NoSlidingExpiration, null);
                }
                
                return service;
            }

            
        }

    }
}
